<script setup lang="tsx">
import { ref, inject } from 'vue';
import { useI18n } from 'vue-i18n';
import UpLoad from '@/components/upLoad/index.vue';
import MyTable from '@/components/myTable/index.vue';
import OperatingBox from '@/components/operatingBox/index.vue';
import QueryBox from '@/components/queryBox/index.vue';
import { formGroup } from '@/components/formDialog/FormDialog';
import FormDialogGroup from '@/components/formDialog/FormDialogGroup.vue';
import { Space, Link, MessagePlugin } from 'tdesign-vue-next';
import { AddIcon, SearchIcon } from 'tdesign-icons-vue-next';
import { getChannelList, add, edit, getInfo, Delete, getDictionaries } from '@/api/bank/rechargeChannel';
import { getName } from '@/utils/tool';
const addDateRange = inject<typeof addDateRange>('addDateRange');
const { t } = useI18n();

const data = ref([]);
const columns = [
  {
    title: '渠道名称',
    colKey: 'name',
  },
  {
    title: '排序',
    colKey: 'sort',
  },
  {
    title: '当前状态',
    colKey: 'state',
  },
  {
    title: '当日充值',
    colKey: 'cardNo',
  },
  {
    title: '充值总额',
    colKey: 'bankBranchName',
  },
  {
    title: '当日提现',
    colKey: 'createTime',
  },
  {
    title: '提交地址',
    colKey: 'submitUrl',
  },
  {
    title: '手续费',
    colKey: 'fee',
    cell: (h: any, { row }: { row: any }) => {
      return new Intl.NumberFormat('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
      }).format(row.fee || 0);
    },
  },
  {
    title: '最小金额',
    colKey: 'minPrice',
    cell: (h: any, { row }: { row: any }) => {
      return new Intl.NumberFormat('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
      }).format(row.minPrice || 0);
    },
  },
  {
    title: '最大金额',
    colKey: 'maxPrice',
    cell: (h: any, { row }: { row: any }) => {
      return new Intl.NumberFormat('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
      }).format(row.maxPrice || 0);
    },
  },
  {
    title: '分类',
    colKey: 'mode',
  },
  {
    title: '客户端',
    colKey: 'type',
  },
  {
    title: '操作',
    colKey: 'op',
  },
];

const pagination = ref({
  defaultCurrent: 1,
  defaultPageSize: 10,
  total: 0,
});

interface FormDataType {
  name: string | null;
  state: string | number | null;
  type: string | number | null;
  mode: string | number | null;
  pageNum: string | number | null;
  pageSize: string | number | null;
}
const INITIAL_QUERYFORM: FormDataType = {
  name: undefined,
  state: undefined,
  type: undefined,
  mode: undefined,
  pageNum: null,
  pageSize: null,
};

const queryForm = ref({ ...INITIAL_QUERYFORM });

const dateRange = ref<string[]>([]);
const balanceRange = ref<[number | null, number | null]>([null, null]);
const render = () => (
  <>
    <OperatingBox>
      <t-button icon={() => <AddIcon />} onClick={() => unAdd()}>
        新增
      </t-button>
    </OperatingBox>
    <QueryBox onReset={onReset} v-model:defaultCurrent={pagination.value.defaultCurrent} onSearch={unGetList}>
      <t-input v-model={queryForm.value.name} placeholder="渠道名称" style="width: 240px;">
        {{
          prefixIcon: () => <SearchIcon />,
        }}
      </t-input>
      <t-select v-model={queryForm.value.state} placeholder="状态">
        <t-option key={1} label="开启" value={1} />
        <t-option key={0} label="关闭" value={0} />
      </t-select>
      <t-select v-model={queryForm.value.mode} placeholder="渠道类型">
        {typeList.value?.map((item) => <t-option key={item.dictValue} label={item.dictLabel} value={item.dictValue} />)}
      </t-select>
      <t-select v-model={queryForm.value.type} placeholder="客户端">
        <t-option key="app" label="APP" value="app" />
        <t-option key="pc" label="PC" value="pc" />
      </t-select>
    </QueryBox>
    <MyTable
      columns={columns}
      data={data.value}
      v-model:pagination={pagination.value}
      rowKey="rcId"
      onUnGetList={unGetList}
    >
      {{
        state: (slotProps: any) => (
          <t-switch
            key={slotProps.row.rcId}
            value={slotProps.row.state}
            onChange={() => unEditState(slotProps)}
            size="large"
            customValue={[1, 0]}
            label={['开', '关']}
          ></t-switch>
        ),
        mode: (slotProps: any) => <div>{getName('dictValue', slotProps.row.mode, typeList.value, 'dictLabel')}</div>,
        type: (slotProps: any) => (
          <div>
            {getName(
              'value',
              slotProps.row.type,
              [
                { value: 'app', key: 'APP' },
                { value: 'pc', key: 'PC' },
              ],
              'key',
            )}
          </div>
        ),
        op: (slotProps: any) => (
          <Space>
            <Link theme="primary" onClick={() => unEdit(slotProps)}>
              修改
            </Link>
            <Link theme="danger" onClick={() => deleteClickOp(slotProps, false)}>
              {t('pages.detailCard.detail.form.delete')}
            </Link>
          </Space>
        ),
      }}
    </MyTable>
  </>
);

const unGetList = async () => {
  try {
    queryForm.value.pageNum = pagination.value.defaultCurrent;
    queryForm.value.pageSize = pagination.value.defaultPageSize;
    const res = await getChannelList({
      ...addDateRange?.(queryForm.value, dateRange.value),
    });
    data.value = res.rows;
    pagination.value = {
      ...pagination.value,
      total: res.total,
    };
  } catch (e) {
    console.log(e);
  }
};

// 获取渠道类型
const typeList = ref([]);
// 获取类型
const unGetDictionaries = () => {
  getDictionaries({}).then((res: any) => {
    typeList.value = res.data;
    unGetList();
  });
};
unGetDictionaries();

const onReset = () => {
  queryForm.value = { ...INITIAL_QUERYFORM };
  balanceRange.value = [null, null];
  unGetList();
};
/** 添加对话框 */
const formObj = new formGroup();
const unAdd = async () => {
  try {
    formObj.show('添加充值渠道', {}, '添加充值渠道');
  } catch (e) {
    console.error(e);
    MessagePlugin.error(e);
  }
};

formObj.add<any>(
  '添加充值渠道',
  '添加充值渠道',
  {},
  async (body) => {
    await add(body.data);
    unGetList();
  },
  {
    name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
  },
  '26%',
);

// 详情
const unEdit = async (slotProps: any) => {
  try {
    let res = await getInfo(slotProps.row.rcId);
    formObj.show(
      '编辑充值渠道',
      {
        ...res.data,
      },
      '编辑充值渠道',
    );
  } catch (e) {
    console.error(e);
    MessagePlugin.error(e);
  }
};

formObj.add<any>(
  '编辑充值渠道',
  '编辑充值渠道',
  {},
  async (body) => {
    await edit(body.data);
    unGetList();
  },
  {
    name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
  },
  '26%',
);

// 删除
const confirmVisible = ref(false);
const deleteId = ref([]);
const onConfirmDelete = () => {
  let ids = deleteId.value.join(',');
  Delete(ids).then(() => {
    confirmVisible.value = false;
    MessagePlugin.success('删除成功');
    unGetList();
  });
};

const deleteClickOp = (value: any, isSingle: boolean) => {
  if (isSingle && !value.length) {
    MessagePlugin.warning('请先勾选数据');
    return;
  }
  confirmVisible.value = true;
  deleteId.value = isSingle ? value : [value.row.rcId];
};

// 修改状态
const unEditState = async (slotProps: any) => {
  slotProps.row.state = slotProps.row.state == 1 ? 0 : 1;
  edit(slotProps.row).then(() => {
    MessagePlugin.success('操作成功');
    unGetList();
  });
};
</script>

<template>
  <div>
    <render />
    <FormDialogGroup :form-obj="formObj">
      <template #default="{ formData, item }">
        <!-- 添加渠道对话框 -->
        <template v-if="item == '添加充值渠道' || item == '编辑充值渠道'">
          <t-form-item label="名称" name="name">
            <t-input v-model="formData.name" placeholder="请输入名称" />
          </t-form-item>
          <t-form-item label="编码" name="code">
            <t-input v-model="formData.code" placeholder="请输入编码" />
          </t-form-item>
          <t-form-item label="提交地址" name="submitUrl">
            <t-input v-model="formData.submitUrl" placeholder="请输入提交地址" />
          </t-form-item>
          <t-form-item label="固定金额" name="fixed">
            <div class="capital">
              <t-input-number v-model="formData.fixed" placeholder="请输入充值渠道固定金额" />
            </div>
          </t-form-item>
          <t-form-item label="最小金额" name="minPrice">
            <div class="capital">
              <t-input-number v-model="formData.minPrice" placeholder="请输入充值渠道最小金额" />
            </div>
          </t-form-item>
          <t-form-item label="最大金额" name="maxPrice">
            <div class="capital">
              <t-input-number v-model="formData.maxPrice" placeholder="请输入充值渠道固定金额" />
            </div>
          </t-form-item>
          <t-form-item label="手续费" name="fee">
            <div class="capital">
              <t-input-number v-model="formData.fee" placeholder="请输入手续费" suffix="%" />
            </div>
          </t-form-item>
          <t-form-item label="渠道类型" name="mode">
            <t-select v-model="formData.mode" placeholder="请选择渠道类型">
              <t-option
                v-for="item in typeList"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue"
              />
            </t-select>
          </t-form-item>
          <t-form-item label="所属客户端" name="type">
            <t-select v-model="formData.type" placeholder="请选择所属客户端">
              <t-option key="app" label="APP" value="app" />
              <t-option key="pc" label="PC" value="pc" />
            </t-select>
          </t-form-item>
          <t-form-item label="排序" name="sort">
            <div class="capital">
              <t-input-number v-model="formData.sort" placeholder="请输入排序" />
            </div>
          </t-form-item>
          <t-form-item label="状态" name="state">
            <t-select v-model="formData.state" placeholder="请选择状态">
              <t-option :key="1" label="开启" :value="1" />
              <t-option :key="0" label="关闭" :value="0" />
            </t-select>
          </t-form-item>
          <t-form-item label="银行图标" name="qrcode">
            <UpLoad v-model:image="formData.qrcode" :key="formData.qrcode"></UpLoad>
          </t-form-item>
        </template>
      </template>
    </FormDialogGroup>
    <t-dialog
      v-model:visible="confirmVisible"
      header="确认删除当前所选项目？"
      body="删除后，数据将被清空，且无法恢复"
      @confirm="onConfirmDelete"
    />
  </div>
</template>

<style lang="less" scoped>
.capital .t-input-number.t-input-number--row {
  width: 314px;
  display: flex;
  align-items: center;
  padding: 0 38px;

  .t-button.t-button--variant-outline.t-button--theme-default.t-button--shape-square.t-button--icon-only {
    width: 38px;
    height: 38px;
  }
}
</style>

<style>
.capital .t-input-number .t-input.t-align-center {
  width: 230px !important;
}
</style>
